﻿using CSV;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Scans : System.Web.UI.Page
{
    int _serviceId = 0;
    private int pageumber = 0;
    private int _count = 0;
    private int _currCount = 0;
    private int _currCountNext = 0;
    ProxyWrapper.UserProxy.UserDetails _objUser = null;
    ProxyWrapper.ScansServiceWrapper _wrp = null;
    protected void Page_Load(object sender, EventArgs e)
    {


        try
        {
            _serviceId = Convert.ToInt32(Request.QueryString["service"] != null ? Request.QueryString["service"].ToString() : "0");
            if (Session["userObject"] == null)
            {
                Response.Redirect("Default.aspx", false);
            }
            else
            {
                // LoadData();
                //_lstScan[0].
            }
            if (Request.QueryString["type"] != null)
            {
                ExportData(Request.QueryString["type"].ToString());
            }
        }
        catch (Exception ex)
        {

        }
    }

    private List<ProxyWrapper.ScansProxy.Scans> LoadData()
    {
        _objUser = ((ProxyWrapper.UserProxy.UserDetails)Session["UserObject"]);
        _wrp = new ProxyWrapper.ScansServiceWrapper();
        ProxyWrapper.ScansProxy.SearchParams _param = new ProxyWrapper.ScansProxy.SearchParams();
        _param.ClienId = _objUser.ClientId;
        _param.DeviceIdsList = Request["d"] != null ? Request["d"].ToString() : null;
        _param.FromDate = Request["sd"] != null ? Request["sd"].ToString() : null;
        _param.FromTime = Request["st"] != null ? Request["st"].ToString() : null;
        _param.HashCode = _objUser.HashCode;
        _param.ServiceIdsList = Request["s"] != null ? Request["s"].ToString() : null;

        string[] devices = Request["d[]"] != null ? Request["d[]"].ToString().Split(',') : null;
        string[] services = Request["s[]"] != null ? Request["s[]"].ToString().Split(',') : null;
        string[] users = Request["u[]"] != null ? Request["u[]"].ToString().Split(',') : null;

        string studentNum = Request["q"] != null ? Request["q"].ToString() : null;
        int stuNum = 0;
        if (int.TryParse(studentNum, out stuNum) && stuNum > 0)
        {
            _param.StudentIdNumber = stuNum;
        }
        else
        {
            _param.StudentName = studentNum;
        }
        string fromDateTIme = (Request["sd"] != null ? Request["sd"].ToString() : "") + " " + (Request["st"] != null ? Request["st"].ToString() : "");
        string toDatTIme = (Request["ed"] != null ? Request["ed"].ToString() : "") + " " + (Request["et"] != null ? Request["et"].ToString() : "");
        _param.ToDate = Request["ed"] != null ? Request["ed"].ToString() : null;
        _param.ToTime = Request["et"] != null ? Request["et"].ToString() : null;
        _param.UsersList = Request["u"] != null ? Request["u"].ToString() : null;
        List<ProxyWrapper.ScansProxy.Scans> _lstScan = _wrp.ListScans(_param);
        if (_lstScan != null && _lstScan.Count > 0)
        {

            if (_serviceId > 0)
            {
                _lstScan = _lstScan.Where(m => m.ServiceId == _serviceId).ToList();
            }
            if (!string.IsNullOrWhiteSpace(fromDateTIme))
            {
                DateTime _fromDate = Convert.ToDateTime(fromDateTIme);
                _lstScan = _lstScan.Where(m => Convert.ToDateTime(m.CreateDate) >= _fromDate).ToList();
            }
            if (!string.IsNullOrWhiteSpace(toDatTIme))
            {
                DateTime _toDate = Convert.ToDateTime(toDatTIme);
                _lstScan = _lstScan.Where(m => Convert.ToDateTime(m.CreateDate) <= _toDate).ToList();
            }
            if (stuNum > 0)
            {
                _lstScan = _lstScan.Where(m => m.StudentIdNumber == stuNum).ToList();
            }
            else if (!string.IsNullOrWhiteSpace(studentNum))
            {
                _lstScan = _lstScan.Where(m => m.FirstName.ToUpper().Contains(studentNum.ToUpper()) || m.LastName.ToUpper().Contains(studentNum.ToUpper())).ToList();
            }
            IEnumerable<ProxyWrapper.ScansProxy.Scans> tmpScan = null;
            if (devices != null)
            {
                tmpScan = from order in _lstScan
                          where devices.Contains(order.DeviceId)
                          select order;
                if (tmpScan != null)
                    _lstScan = tmpScan.ToList<ProxyWrapper.ScansProxy.Scans>();
            }
            if (services != null)
            {
                tmpScan = from order in _lstScan
                          where services.Contains(order.ServiceId.ToString())
                          select order;
                if (tmpScan != null)
                    _lstScan = tmpScan.ToList<ProxyWrapper.ScansProxy.Scans>();
            }
            if (users != null)
            {
                tmpScan = from order in _lstScan
                          where users.Contains(order.UserId.ToString())
                          select order;
                if (tmpScan != null)
                    _lstScan = tmpScan.ToList<ProxyWrapper.ScansProxy.Scans>();
            }
            _count = _lstScan.Count;
            _currCount = 1;
            _currCountNext = dataPaging.PageSize;
            if (Request.QueryString["pageNumber"] != null && Convert.ToInt32(Request.QueryString["pageNumber"].ToString()) > 0)
            {
                pageumber = Convert.ToInt32(Request.QueryString["pageNumber"].ToString());
            }
            else
            {
                pageumber = 1;
            }

            _currCountNext = dataPaging.PageSize * pageumber;
            //  _currCountNext = _currCountNext <= _count ? _currCountNext : _count;
            if (_currCountNext <= _count)
            {
                _currCount = _currCountNext - dataPaging.PageSize + 1;
            }
            else
            {
                _currCountNext = _count;
                _currCount = (dataPaging.PageSize * (pageumber - 1)) + 1;
            }



            //  lstvwScans.DataSource = _lstScan;
            // lstvwScans.DataBind();
            return _lstScan;

        }
        return null;
    }
    internal string GetName(string fname, string lname)
    {
        if (!string.IsNullOrWhiteSpace(fname) && !string.IsNullOrWhiteSpace(lname))
            return fname + " " + lname;
        else if (!string.IsNullOrWhiteSpace(fname))
            return fname;
        else if (!string.IsNullOrWhiteSpace(lname))
            return lname;
        else
            return " ";
    }
    internal string GetCount()
    {
        if (_count > 0)
            return "Showing " + _currCount + " - " + _currCountNext.ToString() + " of " + _count.ToString() + " scans.";
        else
            return " ";


    }
    internal string GetValidityImage(int code)
    {
        switch (code)
        {
            case 1:
                return "Images/red.jpg";
            case 2:
                return "Images/green.jpg";
            case 3:
                return "Images/brown.jpg";
            case 4:
                return "Images/yellow.jpg";
            default:
                return "Images/red.jpg";
        }
    }

    public void ExportData(string _type)
    {
        Decimal tmpNum = 0;
        Decimal sum = 0;
        List<ProxyWrapper.ScansProxy.Scans> _lstScan = LoadData();
        if (_lstScan != null)
        {
            //CreateCSV(_type, ref tmpNum, ref sum, _lstScan);
            StringBuilder sb = new StringBuilder();
            MemoryStream stream = new MemoryStream();
            using (StreamWriter str = new StreamWriter(stream,Encoding.UTF8))
            {
                sb.Append("Scan ID");
                sb.Append(",");
                sb.Append("Device Name");
                sb.Append(",");
                sb.Append("Service Name");
                sb.Append(",");
                sb.Append("User name");
                sb.Append(",");
                sb.Append("Student#");
                sb.Append(",");
                sb.Append("First Name");
                sb.Append(",");
                sb.Append("Last Name");
                sb.Append(",");
                sb.Append("Grade");
                sb.Append(",");
                sb.Append("Validity");
                sb.Append(",");
                sb.Append("Note1");
                sb.Append(",");
                sb.Append("Note2");
                sb.Append(",");
                sb.Append("Note3");
                sb.Append(",");
                sb.Append("Note4");
                sb.Append(",");
                sb.Append("Timestamp Scanned");
                sb.Append(",");
                sb.Append("Timestamp Received");
                sb.Append(",");
                sb.Append("Scan Type");
                str.WriteLine(sb.ToString());
                for (int i = 0; i < _lstScan.Count; i++)
                {
                    sb = new StringBuilder();
                    sb.Append(_lstScan[i].ScanId.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].DeviceName.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].ServiceName.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].UserName.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].StudentIdNumber.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].FirstName.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].LastName.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].Grade.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].ValidityCode.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].Note1.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].Note2.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].Note3.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].Note4.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].CreateDate.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].CreateDate.ToString());
                    sb.Append(",");
                    sb.Append(_lstScan[i].ResponseValue.Trim().ToLower().Contains("duplicate") ? "Duplicate" : " ");
                    str.WriteLine(sb.ToString());
                    if (Decimal.TryParse(_lstScan[i].Note1, out tmpNum))
                        sum = sum + tmpNum;
                }
                if (sum>0)
                {
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append("Total");
                    sb.Append(",");
                    sb.Append(" $" + sum.ToString());
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    sb.Append(",");
                    sb.Append(" ");
                    str.WriteLine(sb.ToString());
                }
                str.Flush();
                stream.Seek(0, SeekOrigin.Begin);
                if (_type == "email")
                {
                    EmailData(stream);
                }
                else
                {
                    SaveAsData(stream);
                }
            }
        }
    }

    private void CreateCSV(string _type, ref Int64 tmpNum, ref Int64 sum, List<ProxyWrapper.ScansProxy.Scans> _lstScan)
    {

        MemoryStream stream = new MemoryStream();

        using (CsvFileWriter writer = new CsvFileWriter(stream))
        {
            CsvRow row = new CsvRow();
            row.Add("Scan ID");
            row.Add("Device Name");
            row.Add("Service Name");
            row.Add("User name");
            row.Add("Student#");
            row.Add("First Name");
            row.Add("Last Name");
            row.Add("Grade");
            row.Add("Validity");
            row.Add("Note1");
            row.Add("Note2");
            row.Add("Note3");
            row.Add("Note4");
            row.Add("Timestamp Scanned");
            row.Add("Timestamp Received");
            writer.WriteRow(row);
            for (int i = 0; i < _lstScan.Count; i++)
            {
                row = new CsvRow();
                row.Add(_lstScan[i].ScanId.ToString());
                row.Add(_lstScan[i].DeviceName.ToString());
                row.Add(_lstScan[i].ServiceName.ToString());
                row.Add(_lstScan[i].UserName.ToString());
                row.Add(_lstScan[i].StudentIdNumber.ToString());
                row.Add(_lstScan[i].FirstName.ToString());
                row.Add(_lstScan[i].LastName.ToString());
                row.Add(_lstScan[i].Grade.ToString());
                row.Add(_lstScan[i].ValidityCode.ToString());
                row.Add(_lstScan[i].Note1.ToString());
                row.Add(_lstScan[i].Note2.ToString());
                row.Add(_lstScan[i].Note3.ToString());
                row.Add(_lstScan[i].Note4.ToString());
                row.Add(_lstScan[i].CreateDate.ToString());
                row.Add(_lstScan[i].CreateDate.ToString());
                writer.WriteRow(row);
                if (Int64.TryParse(_lstScan[i].Note1, out tmpNum))
                {
                    sum = sum + tmpNum;
                }
            }
            if (sum > 0)
            {
                row = new CsvRow();
                row.Add(" ");
                row.Add(" ");
                row.Add(" ");
                row.Add(" ");
                row.Add(" ");
                row.Add(" ");
                row.Add(" ");
                row.Add(" ");
                row.Add("Total:");
                row.Add(sum.ToString());
                row.Add(" ");
                row.Add(" ");
                row.Add(" ");
                row.Add(" ");
                row.Add(" ");
                writer.WriteRow(row);
            }
            if (_type == "email")
            {
                EmailData(stream);
            }
            else
            {
                SaveAsData(stream);
            }
        }

    }

    private void SaveAsData(MemoryStream stream)
    {
        try
        {
            //StreamReader _reader = new StreamReader(stream);
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=scans.csv");
            Response.Charset = "";
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.ContentType = "application/vnd.xls";
            Response.BinaryWrite(stream.ToArray());
            Response.End();
        }
        catch (Exception ex)
        { }
    }

    private void EmailData(MemoryStream stream)
    {
        Mailer.Emailer objMail = new Mailer.Emailer();
        stream.Seek(0, SeekOrigin.Begin);
        objMail.File = new System.Net.Mail.Attachment(stream, "Scans.csv", "application/vnd.xls");
        objMail.To = _objUser.EmailId;
        objMail.Subject = "SSICA - Scans Export";
        objMail.MailBody = "Dear " + _objUser.EmailId + ", <br/><br/><br/>" +
                            "The SSICA scans you chose to export are attached to this email as a CSV file.<br/><br/><br/>" +
                            "This is an automated message. Please do not reply to this email. If you need help, please contact us at support@ssica.org.<br/><br/><br/><br/>" +
                            "Thanks,<br/>" +
                            "The SSICA Team";
        try
        {

            objMail.SendMail();
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
        }
        finally
        {

        }
    }
    protected void dataPaging_PreRender(object sender, EventArgs e)
    {
        try
        {
            lstvwScans.DataSource = LoadData();
            lstvwScans.DataBind();
        }
        catch (Exception)
        {
        }
    }
}